<template>
  <div style="padding-top: 100px">
    <uploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import uploadExcel from '@/components/updateExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployees } from '@/api/employee'
export default {
  name: 'VueAdminTemplateEmpExcel',
  components: {
    uploadExcel
  },

  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 拖拽成功后
    async handleSuccess({ results }) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      // console.log(results) [{'姓名'：'张三','工号':'9002'},{...}...}]
      // 目标：将results映射到新的数组,在新数组中通过枚举转成英文的，深拷贝
      // item：{'姓名'：'张三','工号':'9002'}
      /*  const res = results.map(item => {
        const obj = {}
        // zhKeys:['姓名','工号']
        const zhKeys = Object.keys(item)
        // ele:姓名
        zhKeys.forEach(ele => {
          const enKeys = mapInfo[ele]
          obj[enKeys] = item[ele]
        })
        return obj
      })
      console.log(res) */
      // 将原数组映射到新的数组
      /* const array = results.map(item => {
        const obj = {}
        // ['姓名','工号']
        const zhKeys = Object.keys(item)
        zhKeys.forEach(ele => {
          const enKey = mapInfo[ele]
          obj[enKey] = item[ele]
        })
        return obj
      })
      console.log(array) */
      // 深拷贝 results:[{'姓名':'张三','工号':'1101'},{'姓名':'李四','工号':'1102'},...]
      const array = results.map((item) => {
        const obj = {}
        // 取对象中所有的属性值
        // zhKeys:['姓名','工号']
        const zhKeys = Object.keys(item)
        // 通过遍历数组，输出到obj中
        zhKeys.forEach((ele) => {
          // 转英文
          const enKey = mapInfo[ele]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            obj[enKey] = formatExcelDate(item[ele])
          } else {
            obj[enKey] = item[ele]
          }
        })
        return obj
      })
      console.log(array)
      // 上传文件（向后台发请求）
      const res = await importEmployees(array).catch(e => e)
      console.log(res)
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)
      // console.log(res)
      // 返回上一级
      this.$router.back()
    }
  }
}
</script>

<style lang="scss" scoped></style>
